package com.shuai.api_platform.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

//@Component
public class RandomNumManager_bak2 {

    private final ReentrantLock lock = new ReentrantLock(false);

    /**
     * 随机数管理器
     */
    private final HashMap<String, List<Long>> randomManager = new HashMap<>();


    /**
     * 管理器中是否存在该随机数
     *
     * @param key    map的key值
     * @param random 待验证的随机数
     * @return key对应的值下是否包含该随机数 -- boolean
     */
    public boolean hasRandomVal(String key, Long random) {
        lock.lock();
        try {
            List<Long> list;
            if (randomManager.containsKey(key) && (list = randomManager.get(key)) != null) {
                return list.contains(random);
            }
            return false;
        } finally {
            lock.unlock();
        }
    }


    /**
     * 向随机数管理器中添加元素
     *
     * @param key    key
     * @param random 待添加的随机数
     * @return 返回添加成功与否    -- boolean
     */
    public boolean put(String key, long random) {
        lock.lock();

        try {
            List<Long> list = getList(key);
            if (!list.contains(random)) {
                list.add(random);
                return true;
            }
            return false;
        } finally {
            lock.unlock();
        }
    }


    /**
     * 根据key值获取对应的随机数管理集合
     *
     * @param key key
     * @return key值对应的随机数管理集合
     */
    private List<Long> getList(String key) {
        if (key == null) {
            throw new NullPointerException();
        }
        if (!randomManager.containsKey(key)) {
            randomManager.put(key, new ArrayList<>());
        }
        return randomManager.get(key);
    }

}
